package com.pet.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pet.common.constants.MQConstants;
import com.pet.common.exception.LeadNewsException;
import com.pet.model.article.pojos.ApAuthor;
import com.pet.model.behavior.dtos.FollowBehaviorDto;
import com.pet.model.common.dtos.ResponseResult;
import com.pet.model.common.enums.AppHttpCodeEnum;
import com.pet.model.user.dtos.UserRelationDto;
import com.pet.model.user.pojos.ApUser;
import com.pet.model.user.pojos.ApUserFan;
import com.pet.model.user.pojos.ApUserFollow;
import com.pet.user.feign.ApAuthorFeign;
import com.pet.user.mapper.ApUserFanMapper;
import com.pet.user.mapper.ApUserFollowMapper;
import com.pet.user.service.ApUserFollowService;
import com.pet.utils.common.JsonUtils;
import com.pet.utils.threadlocal.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * APP用户关注信息表 服务实现类
 * </p>
 */
@Service
@Transactional
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {

    @Autowired
    private ApAuthorFeign apAuthorFeign;
    @Autowired
    private ApUserFollowMapper apUserFollowMapper;
    @Autowired
    private ApUserFanMapper apUserFanMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult userFollow(UserRelationDto dto) {
        ApUser user = (ApUser) ThreadLocalUtils.get();
        if(user==null){
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApAuthor apAuthor = apAuthorFeign.findOne(dto.getAuthorId());
        if(apAuthor==null){
            throw new LeadNewsException(404,"该作者已被移除");
        }
        //取出作者的app用户ID
        Integer authorUserId = apAuthor.getUserId();
        //3.判断关注还是取消关注
        if(dto.getOperation().equals(0)){
            //3.1 关注。先查询是否存在关注记录，没有则新增记录；先查询是否存在粉丝记录，没有则新增记录
            QueryWrapper<ApUserFollow> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",user.getId());
            queryWrapper.eq("follow_id",authorUserId);
            Integer count = apUserFollowMapper.selectCount(queryWrapper);
            if(count>0){
                throw new LeadNewsException(500,"你已关注，无需重复关注");
            }
            ApUserFollow apUserFollow = new ApUserFollow();
            apUserFollow.setUserId(user.getId());
            apUserFollow.setFollowId(authorUserId);
            apUserFollow.setFollowName(apAuthor.getName());
            apUserFollow.setLevel(1);
            apUserFollow.setIsNotice(0);
            apUserFollow.setCreatedTime(new Date());
            apUserFollowMapper.insert(apUserFollow);

            QueryWrapper<ApUserFan> apUserFanQueryWrapper = new QueryWrapper<>();
            apUserFanQueryWrapper.eq("user_id",authorUserId);
            apUserFanQueryWrapper.eq("fans_id",user.getId());
            count = apUserFanMapper.selectCount(apUserFanQueryWrapper);
            if(count>0){
                throw new LeadNewsException(500,"已经存在粉丝记录");
            }
            ApUserFan apUserFan = new ApUserFan();
            apUserFan.setUserId(authorUserId);
            apUserFan.setFansId(user.getId());
            apUserFan.setFansName(apAuthor.getName());
            apUserFan.setLevel(0);
            apUserFan.setCreatedTime(new Date());
            apUserFan.setIsDisplay(1);
            apUserFan.setIsShieldLetter(0);
            apUserFan.setIsShieldComment(0);
            apUserFanMapper.insert(apUserFan);

            FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
            followBehaviorDto.setArticleId(dto.getArticleId());
            followBehaviorDto.setFollowId(authorUserId);
            followBehaviorDto.setUserId(user.getId());

            kafkaTemplate.send(MQConstants.FOLLOW_BEHAVIOR_TOPIC, JsonUtils.toString(followBehaviorDto));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            //3.2 取消关注。删除关注记录和粉丝记录

            //查询关注记录，然后删除
            QueryWrapper<ApUserFollow> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",user.getId());
            queryWrapper.eq("follow_id",authorUserId);
            apUserFollowMapper.delete(queryWrapper);
            //查询粉丝记录，并删除
            QueryWrapper<ApUserFan> apUserFanQueryWrapper = new QueryWrapper<>();
            apUserFanQueryWrapper.eq("user_id",authorUserId);
            apUserFanQueryWrapper.eq("fans_id",user.getId());
            apUserFanMapper.delete(apUserFanQueryWrapper);

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }

    @Override
    public ResponseResult<ApUserFollow> getUserFollow(Integer userId, Integer followId) {
        QueryWrapper<ApUserFollow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("follow_id",followId);

        return ResponseResult.okResult(getOne(queryWrapper));
    }
}
